<template>
  <div>
    <div><h1>商品列表</h1></div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="关键词"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadList">搜索</el-button>
          <el-button type="primary" @click="onDeleteBatch">批量删除</el-button>
          <el-button type="primary" @click="handlerAddProd">添加商品</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="ID" width="50" />
        <el-table-column prop="prodSpu" label="SPU" width="100" />
        <el-table-column prop="kindName" label="商品种类" width="100" />
        <el-table-column prop="typeName" label="类型" width="100" />
        <el-table-column prop="prodStatus" label="商品状态" width="120" />
        <el-table-column prop="prodName" label="商品名称" width="120" />
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="unitName" label="单位" width="100" />
        <el-table-column prop="tagName" label="标志" width="100" />
        <el-table-column prop="appr" label="供应商" width="120" />
        <el-table-column prop="prodImage" label="图片" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.prodImage != null && scope.row.prodImage != ''"
              :src="scope.row.prodImage"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="primary" @click="handlerUpdateProd(scope.row)"
              >商品明细</el-button
            >
            <el-button type="primary" @click="handlerProdInfo(scope.row)"
              >商品附件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
        <el-form :model="AddForm" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="AddForm.prodKind">
              <el-radio
                v-for="item in typeList"
                :value="item.dictValue"
                :key="item.dictValue"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="AddForm.prodType"
              :data="ClassList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="AddForm.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品SUP"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="AddForm.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select v-model="AddForm.brandId" placeholder="请选择">
              <el-option
                v-for="item in brandList"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select v-model="AddForm.unitId" placeholder="请选择">
              <el-option
                v-for="item in unitList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select v-model="AddForm.tagId" placeholder="请选择">
              <el-option
                v-for="item in tagList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="appr"
          >
            <el-input v-model="AddForm.appr" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadImages"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog v-model="ProdInfoVisible" title="添加商品附件" width="500">
        <el-form :model="AddProdInfo" ref="ruleFormRef" :rules="rulesInfo">
          <el-form-item
            label="商品轮播图"
            :label-width="InfoLabelWidth"
            prop="attaImages"
          >
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/prod/type/uploadImages"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item
            label="商品视频"
            :label-width="InfoLabelWidth"
            prop="attaVideo"
          >
            <el-upload
              v-model:file-list="videoList"
              class="upload-demo"
              action="http://localhost:10010/prod/type/uploadImages"
              multiple
              :on-preview="handlePreview"
              :on-remove="handlevideoRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :headers="headers"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮播的视频介绍，最大限制20MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上架时间"
            :label-width="InfoLabelWidth"
            prop="upFlag"
          >
            <el-radio-group v-model="AddProdInfo.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="AddProdInfo.upFlag == 1"
            :label-width="InfoLabelWidth"
          >
            <el-date-picker
              v-model="AddProdInfo.upTime"
              type="datetime"
              placeholder="请选择上架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="定时下架"
            :label-width="InfoLabelWidth"
            prop="downFlag"
          >
            <el-switch
              v-model="AddProdInfo.downFlag"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item
            v-if="AddProdInfo.downFlag == 1"
            :label-width="InfoLabelWidth"
          >
            <el-date-picker
              v-model="AddProdInfo.downTime"
              type="datetime"
              placeholder="请选择下架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitFormInfo(ruleFormRef)">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getprodListPage,
  getDeleteBatch,
  getDictList,
  getTreeselect,
  getBrandList,
  getAddProd,
  getAddProdAtta,
} from "../api/api";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
const imageUrl = ref("");
const ruleFormRef = ref<FormInstance>();
const fileList = ref<UploadUserFile[]>([]);
const videoList = ref<UploadUserFile[]>([]);
const tableData = ref([]);
const total = ref(0);
const multipleSelection = ref<any[]>([]);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
});
import { useRouter } from "vue-router";
const Router = useRouter();
const headers = {
  token: sessionStorage.getItem("token"),
};

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ProdInfoVisible = ref(false);
const InfoLabelWidth = "140px";

const AddForm = ref({
  appr: "",
  brandId: null,
  createBy: "",
  createTime: "",
  kindName: "",
  prodId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodStatus: 0,
  prodType: null,
  tagId: null,
  unitId: null,
});
const AddProdInfo = ref({
  attaId: null,
  attaImages: "",
  attaVideo: "",
  createBy: "",
  createTime: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
  updateBy: "",
  updateTime: "",
  attaImagesList: [],
});

const typeList = ref([]);
const ClassList = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);

const page = ref({
  pageNum: 1,
  pageSize: 999999,
});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

//自定义校验
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (
    imageUrl.value == null ||
    imageUrl.value.length == 0 ||
    imageUrl.value == ""
  ) {
    callback(new Error("请选择商品图片"));
  } else {
    callback();
  }
};
//添加校验
const rules = reactive<FormRules>({
  prodKind: [
    {
      required: true,
      message: "请选择商品类型",
      trigger: "change",
    },
  ],
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  appr: [{ required: true, message: "请输入商品供应商", trigger: "blur" }],
  prodType: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  brandId: [
    {
      required: true,
      message: "请选择商品品牌",
      trigger: "change",
    },
  ],
  unitId: [
    {
      required: true,
      message: "请选择商品单位",
      trigger: "change",
    },
  ],
  tagId: [
    {
      required: true,
      message: "请选择商品标签",
      trigger: "change",
    },
  ],
  prodImage: [{ required: true, validator: validatePass2, trigger: "blur" }],
});

//商品明细自定义校验
const validatePass1 = (rule: any, value: any, callback: any) => {
  if (fileList.value == null || fileList.value.length == 0) {
    callback(new Error("请选择商品图片"));
  } else {
    callback();
  }
};
const validatePass3 = (rule: any, value: any, callback: any) => {
  if (videoList.value == null || videoList.value.length == 0) {
    callback(new Error("请选择商品视频"));
  } else {
    callback();
  }
};
//添加校验
const rulesInfo = reactive<FormRules>({
  upFlag: [
    {
      required: true,
      message: "请选择商品上架",
      trigger: "change",
    },
  ],

  downFlag: [
    {
      required: true,
      message: "请选择商品下架",
      trigger: "change",
    },
  ],

  attaImages: [{ required: true, validator: validatePass1, trigger: "blur" }],
  attaVideo: [{ required: true, validator: validatePass3, trigger: "blur" }],
});

//上传视频
const handlevideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning("上传失败");
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

//多图片上传
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//商品附件校验
const submitFormInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onAddProdInfo();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//添加商品附件
const onAddProdInfo = () => {
  let images: any = [];
  if (fileList.value.length == 0) {
    ElMessage.error("请选择图片");
  }
  fileList.value.forEach((item) => {
    images.push(item.response.data);
  });

  AddProdInfo.value.attaImages = JSON.stringify(images);

  if (videoList.value.length == 0) {
    ElMessage.error("请选择视频");
  }
  AddProdInfo.value.attaVideo = videoList.value[0].response.data;
  getAddProdAtta(AddProdInfo.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadList();
      ProdInfoVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//添加商品
const onAddProd = () => {
  AddForm.value.prodImage = imageUrl.value;
  getAddProd(AddForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//上传图片成功
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};

//商品明细
const handlerProdInfo = (row: any) => {
  AddProdInfo.value = {
    attaId: null,
    attaImages: "",
    attaVideo: "",
    createBy: "",
    createTime: "",
    downFlag: null,
    downTime: "",
    prodId: null,
    upFlag: null,
    upTime: "",
    updateBy: "",
    updateTime: "",
    attaImagesList: [],
  };
  fileList.value = "";
  videoList.value = "";
  AddProdInfo.value.prodId = row.prodId;
  ProdInfoVisible.value = true;
};

//回显商品信息和明细
const handlerUpdateProd = (row: any) => {
  router.push("/home/prodInfo/" + row.prodId);
};

//商品添加显示添加框
const handlerAddProd = (row: any) => {
  AddForm.value = {
    appr: "",
    brandId: null,
    createBy: "",
    createTime: "",
    kindName: "",
    prodId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodStatus: 0,
    prodType: null,
    tagId: null,
    unitId: null,
  };
  dialogFormVisible.value = true;
};

//校验提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onAddProd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//批量删除
const onDeleteBatch = () => {
  multipleSelection.value;
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择数据");
    return;
  }
  getDeleteBatch(multipleSelection.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

const loadList = () => {
  getprodListPage(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  //获取商品类型数据
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });

  //获取树形分类数据
  getTreeselect().then((res) => {
    if (res.data.code == 200) {
      ClassList.value = res.data.data;
    }
  });
  //获取品牌数据信息
  getBrandList(page.value).then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data.records;
    }
  });

  //获取商品单位数据
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });

  //获取商品标签数据
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });

  loadList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
